package org.alerve.android.resourcebuilder.modules;

import static android.content.Context.LAYOUT_INFLATER_SERVICE;

import org.alerve.android.resourcebuilder.IModule;
import org.alerve.android.resourcebuilder.Layout;
import org.alerve.android.resourcebuilder.AbstractDirector.ModuleClass;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

/**
 * 
 * Concrete implementation of {@link IModule} for {@link ViewGroup} instances
 * 
 * @author pablisco
 * 
 */
@ModuleClass(ViewGroup.class)
public class ViewGroupModule extends DecoratorModule<ViewGroup> {

	private static LayoutInflater inflater;

	public ViewGroupModule() {
		super();
		addModule(new ViewGroupInflator());
		addModule(new ViewGroupPopulator());
	}
	
	private final class ViewGroupInflator
			extends
				InflatorModule<ViewGroup> {

		@Override
		protected boolean inflate(ViewGroup subject, Layout layout) {
			if (layout == null) {
				// if it doesn't have a Layout it may be inside another view in
				// the xml layout
				// TODO should this be logged somewhere?
				return false;
				// throw new InflateException(
				// "The viewgroup must have a aLayout annotation");
			}
			if (inflater == null) {
				Context context = subject.getContext();
				if (context instanceof Activity) {
					inflater = ((Activity) context).getLayoutInflater();
				} else {
					inflater = (LayoutInflater) context
							.getSystemService(LAYOUT_INFLATER_SERVICE);
				}
			}
			inflater.inflate(layout.value(), subject, true);
			return true;
		}

	}

	private final class ViewGroupPopulator
			extends
				PopulatorModule<ViewGroup> {
		@Override
		protected View findViewById(ViewGroup parent, int id) {
			return parent.findViewById(id);
		}
	}

}
